package com.demo.javaDemo.concurrent; 
import java.io.File; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.ForkJoinPool; 
import java.util.concurrent.ForkJoinTask; 
import java.util.concurrent.RecursiveTask; 
public class ForkJoinFileSize{ 
    private final static ForkJoinPool forkJoinPool = new ForkJoinPool(); 
    private static class FileSizeFinder extends RecursiveTask<Long> { 
        final File file; 
        public FileSizeFinder(final File theFile) { 
            file = theFile; 
        } 
        @Override 
        public Long compute() { 
            long size = 0; 
            if (file.isFile()) { 
                size = file.length(); 
            } else { 
                final File[] children = file.listFiles(); 
                if (children != null) { 
                    List<ForkJoinTask<Long>> tasks = new ArrayList<ForkJoinTask<Long>>(); 
                    for (final File child : children) { 
                        if (child.isFile()) { 
                            size += child.length(); 
                        } else { 
                            tasks.add(new FileSizeFinder(child)); 
                        } 
                    } 
                    
                    for (final ForkJoinTask<Long> task : invokeAll(tasks)) { 
                        size += task.join(); 
                    } 
                } 
            } 
            return size; 
        } 
    } 
    public static void main(final String[] args) {
    	File path=new File("c:/Windows");
    	final long start = System.nanoTime();
    	for(File f:path.listFiles()){
    		final long total = forkJoinPool.invoke(new FileSizeFinder(f)); 
    		System.out.println(f.getName()+": " + size(total));
    	}
         
        
        final long end = System.nanoTime(); 
         
        //System.out.println("Time taken: " + (end - start) / 1.0e9); 
    } 
    public static String size(long total){
    	int i=0;
    	String[] units={"B","K","M","G","T","P"};
    	while(total>1024){
    		i++;
    		total/=1024;
    	}
    	return total+units[i];
    }
} 